load "items_fetcher.rb"

class ItemsController < ApplicationController
  layout "standard-layout"

  

  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @item_pages, @items = paginate :items, :per_page => 10
  end

  def show
    @item = Item.find(params[:id])
  rescue
     flash[:error] = 'Error selecting item, redirecting to item list'
     redirect_to :action => :list
  end

  def new
    redirect_to(:action => "fetch")
    #unless @item
    #  @item = Item.new
    #end
  end
  
  def fetch
    if request.get?
      @item = Item.new
    else    
      item = Item.new(params[:item])
      @item = Item.find_by_wowlink(item.wowlink)
      unless @item
        @item = item
      end
      
      if(WowHeadItemsFetcher.fetchItem(@item))     
            
        if @item.save
          flash[:notice] = "Fetch suceeded."  
          redirect_to(:action => "show", :id => @item.id)
        else
          flash[:notice] = "Item already present."  
        end
      else
        flash[:notice] = "Fetch failed."
      #@item = WowHeadItemsFetcher.fetchItem((params[:wowlink])
      end
    end
  end

  def create
    @item = Item.new(params[:item])
    if @item.save
      flash[:notice] = 'Item was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @item = Item.find(params[:id])
  end

  def update
    @item = Item.find(params[:id])
    if @item.update_attributes(params[:item])
      flash[:notice] = 'Item was successfully updated.'
      redirect_to :action => 'show', :id => @item
    else
      render :action => 'edit'
    end
  end

  def destroy
    Item.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end
